import {
  Card,
  Col,
  Modal,
  Row,
  Tree,
  Pagination,
  Spin,
  Empty,
  message,
  Button,
} from "antd";
import { MyModalProps } from "types/modal";
import { gutter } from "../const/keys";
import { ProColumns, ProTable } from "@ant-design/pro-components";
import { useEffect, useState } from "react";
import { useCategoryModel } from "@/models/category";
import { getProductList } from "@/services/ant-design-pro/api";
import { EyeFilled } from "@ant-design/icons";
import { sleep } from "@/utils";
import DetailModal from "../product/DetailModal";
// import { getProductList } from "@/services/product";
type Props = {} & MyModalProps;
const App = (props: Props) => {
  const { onClose = () => {}, onOk = () => {} } = props;
  const [pageNum, setPageNum] = useState(1);
  const [pageSize, setPageSize] = useState(8);
  const [open, setOpen] = useState(false);
  const [data, setData] = useState<any>({});
  const [total, setTotal] = useState(0);
  const [productLoading, setProductLoading] = useState(false);
  const [dataSource, setDataSource] = useState<Record<string, any>[]>([]);
  const [productCategoryId, setProductCategoryId] = useState<number>();
  const { loading, categoryList } = useCategoryModel();
  const [selected, setSelected] = useState<any>({});
  const [query, setQuery] = useState<any>({});
  const maxSize = 5;
  const [size, setSize] = useState(0);
  let status = false;
  const addItem = async (item: any) => {
    const newSelected = { ...selected };
    if (!newSelected[item.id]) {
      if (size >= maxSize) {
        if (!status) {
          message.warning(`最多选择 ${maxSize} 个产品`);
          status = true;
          await sleep(2000);
          status = false;
        }
        return;
      }
      newSelected[item.id] = item;
    } else {
      delete newSelected[item.id];
    }
    setSelected(newSelected);
  };
  const columns: ProColumns<Record<string, any>, "text">[] | undefined = [
    {
      title: "品牌",
      dataIndex: "brand",
      key: "brand",
    },
    {
      title: "型号",
      dataIndex: "modelSpecification",
      key: "modelSpecification",
    },
  ];
  const getData = async () => {
    setSelected({});
    setProductLoading(true);
    const { total, rows } = await getProductList({
      productCategoryId,
      pageNum,
      pageSize,
      ...query,
    });

    setDataSource(rows || []);
    setTotal(total);
    setProductLoading(false);
  };
  useEffect(() => {
    setSize(Object.keys(selected)?.length);
  }, [selected]);
  useEffect(() => {
    getData();
  }, [productCategoryId, pageNum, pageSize, query]);
  return (
    <>
      <Modal
        width={1200}
        open
        title="选择产品"
        okButtonProps={{
          disabled: size <= 0,
        }}
        onOk={() => {
          onOk(selected);
        }}
        onCancel={() => {
          onClose(false);
        }}
      >
        <Row gutter={[gutter, gutter]} wrap={false} style={{ height: 593 }}>
          <Col flex={"250px"}>
            <Card
              loading={loading}
              title="产品分类"
              size="small"
              style={{
                height: "100%",
              }}
            >
              <Tree
                showIcon
                blockNode
                treeData={categoryList}
                onSelect={(a, b) => {
                  const selectedValue = a[0];

                  if (selectedValue) {
                    setProductCategoryId(Number(b.node.value));
                  } else {
                    setProductCategoryId(undefined);
                  }
                }}
              />
            </Card>
          </Col>
          <Col flex={"auto"}>
            <ProTable
              search={{
                labelWidth: "auto",
              }}
              columns={columns}
              tableRender={() => null}
              request={async (query: any) => {
                delete query.current;
                delete query.pageSize;
                console.log(query);
                setQuery(query);
                return {};
              }}
            />

            <Row
              gutter={[gutter, gutter]}
              style={{
                padding: "0 24px",
              }}
            >
              <Col span={24}>
                <div
                  style={{
                    height: 500,
                    overflowX: "hidden",
                    overflowY: "auto",
                  }}
                >
                  <Spin spinning={productLoading}>
                    <Row gutter={[gutter, gutter]} style={{ minHeight: 200 }}>
                      {dataSource?.length <= 0 ? (
                        <Col span={24}>
                          <Row justify="center">
                            <Col>
                              <Empty />
                            </Col>
                          </Row>
                        </Col>
                      ) : null}
                      {dataSource?.map((item) => {
                        return (
                          <Col span={6} key={item.id}>
                            <div
                              className="box"
                              style={{
                                height: 240,
                                cursor: "pointer",

                                border: `2px solid ${
                                  selected?.[item.id]?.id &&
                                  selected?.[item.id]?.id === item.id
                                    ? "#40a9ff"
                                    : "#e5e5e5"
                                }`,
                                color:
                                  selected?.[item.id]?.id &&
                                  selected?.[item.id]?.id === item.id
                                    ? "#40a9ff"
                                    : "",
                                padding: 10,
                                borderRadius: 10,
                              }}
                              onClick={() => {
                                addItem(item);
                              }}
                            >
                              <Row gutter={[gutter, 0]}>
                                <Col span={24} style={{ height: 125 }}>
                                  <Row justify={"center"}>
                                    <Col>
                                      <img
                                        src={item.firstPicFilePath}
                                        alt={item.productName}
                                        style={{
                                          maxWidth: "100%",
                                          maxHeight: 120,
                                        }}
                                      />
                                    </Col>
                                  </Row>
                                </Col>
                                <Col span={24}>
                                  <div
                                    style={{
                                      fontSize: 12,
                                      width: "100%",
                                      overflow: "hidden",
                                      textOverflow: "ellipsis",
                                      whiteSpace: "nowrap",
                                    }}
                                  >
                                    <span title={`品牌：${item.brand}`}>
                                      {item.brand || "--"}
                                    </span>
                                  </div>
                                </Col>

                                <Col span={24}>
                                  <div
                                    title={`型号：${item.modelSpecification}`}
                                    style={{
                                      width: "100%",
                                      overflow: "hidden",
                                      textOverflow: "ellipsis",
                                      whiteSpace: "nowrap",
                                    }}
                                  >
                                    {item.modelSpecification || "--"}
                                  </div>
                                </Col>
                                <Col span={24}>
                                  <div
                                    style={{
                                      width: "100%",
                                      overflow: "hidden",
                                      textOverflow: "ellipsis",
                                      whiteSpace: "nowrap",
                                    }}
                                  >
                                    <strong
                                      title={`产品名称：${item.productName}`}
                                    >
                                      {item.productName || "--"}
                                    </strong>
                                  </div>
                                </Col>
                                <Col span={24}>
                                  <Row justify="space-between">
                                    <Col>
                                      ¥
                                      {((item.supplyPrice || 0) / 100).toFixed(
                                        2
                                      )}
                                    </Col>
                                    <Col>
                                      <Button
                                        style={{
                                          border: "none",
                                        }}
                                        icon={<EyeFilled />}
                                        onClick={(ev) => {
                                          setOpen(true);
                                          setData({ id: item.id });
                                          ev.stopPropagation();
                                        }}
                                      ></Button>
                                    </Col>
                                  </Row>
                                </Col>
                              </Row>
                            </div>
                          </Col>
                        );
                      })}
                    </Row>
                  </Spin>
                </div>
              </Col>
              <Col span={24}>
                <Row justify="center">
                  <Col>
                    <Pagination
                      showTotal={(total) => `共 ${total} 条`}
                      total={total}
                      pageSize={pageSize}
                      current={pageNum}
                      onChange={(page, pageSize) => {
                        setPageNum(page);
                        setPageSize(pageSize);
                      }}
                    />
                  </Col>
                </Row>
              </Col>
            </Row>
          </Col>
        </Row>
        <br />
        <br />
        <br />
      </Modal>
      {open ? (
        <DetailModal
          data={data}
          onClose={() => {
            setOpen(false);
          }}
        />
      ) : null}
    </>
  );
};
export default App;
